package com.example.testcamara;

import androidx.annotation.NonNull;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AppCompatActivity;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.LocaleList;
import android.os.Looper;
import android.os.Message;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.OrientationEventListener;
import android.view.Surface;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;

import java.util.Locale;

public class MainActivity extends AppCompatActivity {
    private CameraController mCameraController;
    private Button mBtnTakePic;
    private Button mBtnRecordVideo;
    private ImageView mIvVideo;
    private final String TAG = "MainActivity";

    private String[] permissions = new String[]{
            Manifest.permission.CAMERA,
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.WRITE_EXTERNAL_STORAGE,
            Manifest.permission.RECORD_AUDIO,
    };

    @Override
    protected void attachBaseContext(Context newBase) {
        // 多语言适配
        super.attachBaseContext(LanguageUtil2.getNewLocalContext(newBase));
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        Log.e("EEDD", "onDestroy");
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
        System.exit(0);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Log.e("EEDD", "" + this + " onCreate：" + LanguageUtil2.getLanCode(this));
        Log.e("EEDD", "" + this + " onCreate：" + getString(R.string.record));
        setContentView(R.layout.activity_main);
//        Log.e("EEDD", "打的：" + Locale.forLanguageTag("zh-Hans").toLanguageTag());
//        Log.e("EEDD", "当前：" + LanguageUtil.getSystemLocal().getLanguage());
//        Log.e("EEDD", "当前：" + LanguageUtil.getSystemLocal().toLanguageTag());

        ActionBar bar = getSupportActionBar();
        bar.hide();
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.
                LayoutParams.FLAG_FULLSCREEN);
        setContentView(R.layout.activity_main);

        PermissionsRequester.getInstance().getPermissions(this, permissions, mPermissionsResult);

        mBtnTakePic = findViewById(R.id.btn_take_pic);
        mBtnTakePic.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Log.e("EEDD", "takepic: " + R.string.takepic);
//                LanguageUtil2.switchLanguage(LanguageUtil2.CN, MainActivity.this, MainActivity.class);
//                Toast.makeText(MainActivity.this, getString(R.string.takepic), Toast.LENGTH_SHORT).show();
                Intent intent = new Intent(MainActivity.this, Camera2Activity.class);
                intent.putExtra(Camera2Activity.ACT, Camera2Activity.TAKE_PIC);
                intent.putExtra(Camera2Activity.FILENAME, "");
                Log.d(TAG, "mBtnTakePic");
                startActivity(intent);
            }
        });

        mBtnRecordVideo = findViewById(R.id.btn_record_video);
        mBtnRecordVideo.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Log.e("EEDD", "record: " + R.string.record);
//                LanguageUtil2.switchLanguage(LanguageUtil2.HK, MainActivity.this, MainActivity.class);
//                Toast.makeText(MainActivity.this, getString(R.string.record), Toast.LENGTH_SHORT).show();
                Intent intent = new Intent(MainActivity.this, Camera2Activity.class);
                intent.putExtra(Camera2Activity.ACT, Camera2Activity.RECORDING_VIDEO);
                intent.putExtra(Camera2Activity.FILENAME, "");
                Log.d(TAG, "mBtnRecordVideo");
                startActivity(intent);
            }
        });

        findViewById(R.id.btn_xxx).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Log.e("EEDD", "abc: " + R.string.abc);
//                LanguageUtil2.switchLanguage(LanguageUtil2.EN, MainActivity.this, MainActivity.class);
//                Toast.makeText(MainActivity.this, getString(R.string.abc), Toast.LENGTH_SHORT).show();
//                Intent intent = new Intent(MainActivity.this, Camera2Activity.class);
//                intent.putExtra(Camera2Activity.ACT, Camera2Activity.RECORDING_VIDEO);
//                intent.putExtra(Camera2Activity.FILENAME, "");
//                Log.d(TAG, "mBtnRecordVideo");
//                startActivity(intent);
            }
        });


//        initFullScreenOrientationChangeListener();
//        RotationListener rotationListener = new RotationListener(this);
////        rotationListener.enable();
//
//        mIvVideo = findViewById(R.id.iv_video);
//        String path = getExternalCacheDir() + "/videorecord/3287c37509027064f0023ad44fd5c2ce.mp4";
//        Log.e("EEDD", path);
////        mIvVideo.setImageBitmap(GeneralUtils.getVideoThumbBmp(path));
//        String md5 = GeneralUtils.getFileMD5(getApplicationContext(), path);
//        Log.e("EEDD", "-> " + md5);
//
//        Log.e("EEDD", "" + GeneralUtils.getFileLength(getApplicationContext(), path));
//
//        test();
    }

    private void test() {
        new Thread(new Runnable() {
            private int add;

            @Override
            public void run() {
                Log.e("EEDD", "" + Looper.myLooper());
//                Looper.prepare();
                Handler handler = new Handler() {
                    @Override
                    public void handleMessage(@NonNull Message msg) {
                        super.handleMessage(msg);
                        switch (msg.what) {
                            case 0:
                                Log.e("EEDD", "222");
                                sendEmptyMessage(0);
                                break;
                        }
                    }
                };
                handler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        Log.e("EEDD", "111");
                        handler.sendEmptyMessage(0);
                    }
                }, 1000);
//                Looper.loop();
            }
        }).start();
    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[]
            permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        PermissionsRequester.getInstance().onRequestPermissionsResult(MainActivity.this, requestCode,
                permissions, grantResults);
    }

    PermissionsRequester.IPermissionsResult mPermissionsResult = new PermissionsRequester.IPermissionsResult() {
        @Override
        public void onResult(boolean passPermissions) {
            String msg = "";
            if (passPermissions) {
                msg = "已授权";
            } else {
                msg = "已取消";
            }
            //Toast.makeText(MainActivity.this, msg, Toast.LENGTH_LONG).show();
        }
    };


    /**
     * 传感器
     */
    private SensorManager mSensorManager;

    /**
     * 加速第传感器，监听感应屏幕旋转
     */
    private FullScreenOrientationChangedListener mSensorEventListener;

    private void initFullScreenOrientationChangeListener() {
        if (mSensorManager == null) {
            mSensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
        }
        if (mSensorEventListener == null) {
            mSensorEventListener = new FullScreenOrientationChangedListener();
        }
        final Sensor accelerometerSensor = mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
        mSensorManager.registerListener(mSensorEventListener, accelerometerSensor, SensorManager.SENSOR_DELAY_NORMAL);
    }

    private void clearFullScreenOrientationChangeListener() {
        if (mSensorManager != null && mSensorEventListener != null) {
            mSensorManager.unregisterListener(mSensorEventListener);
            mSensorEventListener = null;
        }
    }

    private static class FullScreenOrientationChangedListener implements SensorEventListener {
        @Override
        public void onSensorChanged(SensorEvent event) {
            if (event.sensor.getType() == Sensor.TYPE_ACCELEROMETER) {
                float x = event.values[0];
                float y = event.values[1];
                float z = event.values[2];

                // 计算设备的方向
                int orientation = calculateOrientation(x, y, z);

                // 根据设备方向调整录制参数
                if (orientation == Surface.ROTATION_0) {
                    // 竖直方向，例如设备直立
                    Log.e("EDEE", "竖直方向，例如设备直立");
//                    mediaRecorder.setOrientationHint(90);
                } else if (orientation == Surface.ROTATION_90) {
                    // 逆时针旋转90度，例如设备左侧横屏
                    Log.e("EDEE", "逆时针旋转90度，例如设备左侧横屏");
//                    mediaRecorder.setOrientationHint(0);
                } else if (orientation == Surface.ROTATION_180) {
                    // 逆时针旋转180度，例如设备倒立
                    Log.e("EDEE", "逆时针旋转180度，例如设备倒立");
//                    mediaRecorder.setOrientationHint(270);
                } else if (orientation == Surface.ROTATION_270) {
                    // 逆时针旋转270度，例如设备右侧横屏
                    Log.e("EDEE", "逆时针旋转270度，例如设备右侧横屏");
//                    mediaRecorder.setOrientationHint(180);
                }
            }
        }

        private int calculateOrientation(float x, float y, float z) {
            // 根据加速度传感器的值计算设备的方向
            int orientation = Surface.ROTATION_0;

            // 假设设备在水平面上运动，当 x、y、z 值满足特定条件时，可以确定设备的方向
            // 这里只提供一个基本的示例，实际上需要根据具体需求进行适配

            // 检测设备是否处于水平状态
            boolean isHorizontal = Math.abs(x) < 2.0 && Math.abs(y) < 2.0 && z > 9.0;

            if (isHorizontal) {
                // 检测设备的方向
                if (x > 2.0) {
                    orientation = Surface.ROTATION_270; // 右侧横屏
                } else if (x < -2.0) {
                    orientation = Surface.ROTATION_90; // 左侧横屏
                }
            } else {
                // 设备不处于水平状态，可以根据需要进行其他判断
                if (y > 2.0) {
                    orientation = Surface.ROTATION_0; // 设备朝上
                } else if (y < -2.0) {
                    orientation = Surface.ROTATION_180; // 设备朝下
                } else if (z > 9.0) {
                    orientation = Surface.ROTATION_0; // 设备朝上
                } else if (z < -9.0) {
                    orientation = Surface.ROTATION_180; // 设备朝下
                }
            }
            return orientation;
        }

        @Override
        public void onAccuracyChanged(Sensor sensor, int accuracy) {
            // Do Noting
        }
    }


    public static class RotationListener extends OrientationEventListener {

        public RotationListener(Context context) {
            super(context);
        }

        @Override
        public void onOrientationChanged(int orientation) {
            if (orientation == ORIENTATION_UNKNOWN) {
                return;
            }

            // 根据设备方向进行相应的处理
            if (orientation >= 0 && orientation < 45 || orientation >= 315) {
                // 竖屏
                Log.e("EEDD", "竖屏");
            } else if (orientation >= 45 && orientation < 135) {
                // 左横屏
                Log.e("EEDD", "左横屏");
            } else if (orientation >= 135 && orientation < 225) {
                // 反向竖屏
                Log.e("EEDD", "反向竖屏");
            } else if (orientation >= 225 && orientation < 315) {
                // 右横屏
                Log.e("EEDD", "右横屏");
            }
        }
    }

}
